package com.whiteblue.model;

import com.jfinal.plugin.ehcache.CacheKit;
import com.whiteblue.common.Const;
import com.whiteblue.ext.jfinal.Model;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA. Author: I have A dream Date: 13-3-26
 */
public class User extends Model<User> {
	public static final User dao = new User();
	private static final String USER_CACHE = "user";

	public User() {
		super(USER_CACHE);
	}

	/* get */
	public User get(int id) {
		return loadModel(id);
	}

	public User getByPassword(String password) {
		return dao.findFirst(
				"select id, username, password from user where password=?",
				getMD5(password.getBytes()));
	}

	public User getByPassword(String id, String password) {
		return dao
				.findFirst(
						"select id, username, password from user where id=? and password=?",
						id, getMD5(password.getBytes()));
	}

	/* other */
	public void mySave() {
		this.filterText("username", "headImg", "blogUrl", "feeling");
		String password = getMD5(this.getStr("password").getBytes());
		this.set("password", password).set("registDate", new Date());
		this.save();
	}

	public void myUpdate() {
		this.filterText("username", "headImg", "blogUrl", "feeling");
		this.update();
		removeThisCache(this.getInt("id"));
	}

	public boolean containId(String id) {
		return dao.findFirst("select id from user where id=? limit 1", id) != null;
	}

	public boolean containUsername(String username) {
		return dao.findFirst(
				"select username from user where username=? limit 1", username) != null;
	}

	public boolean containUsernameExceptThis(int userID, String username) {
		return dao.findFirst(
				"select username from user where username=? and id!=? limit 1",
				username, userID) != null;
	}

	/* getter */
	public boolean getIsAdmin(int ID) {
		return Const.ADMIN_ID == ID;
	}

	/* private */
	private String getMD5(byte[] src) {
		StringBuffer sb = new StringBuffer();
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(src);
			for (byte b : md.digest())
				sb.append(Integer.toString(b >>> 4 & 0xF, 16)).append(
						Integer.toString(b & 0xF, 16));
		} catch (NoSuchAlgorithmException e) {
		}
		return sb.toString();
	}

	/* cache */
	private void removeThisCache(int id) {
		CacheKit.remove(USER_CACHE, id);
	}
}
